#!/usr/bin/env node

const http = require('http');

// 测试项目详情API
function testProjectDetailAPI() {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/projects/cmenkhaca0000ltd55p0jylfd',
      method: 'GET'
    };

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve({
            status: res.statusCode,
            data: jsonData
          });
        } catch (e) {
          reject(new Error('Failed to parse JSON response'));
        }
      });
    });

    req.on('error', reject);
    req.end();
  });
}

// 测试页面渲染
function testPageRendering() {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 3000,
      path: '/projects/cmenkhaca0000ltd55p0jylfd',
      method: 'GET'
    };

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        resolve({
          status: res.statusCode,
          hasSkeleton: data.includes('skeleton') || data.includes('animate-pulse'),
          hasProjectName: data.includes('TAPD 电子产品研发管理系统'),
          hasError: data.includes('error') || data.includes('Error') || data.includes('404'),
          pageContent: data.substring(0, 500) + '...' // Truncated content
        });
      });
    });

    req.on('error', reject);
    req.end();
  });
}

async function runTests() {
  console.log('🔍 开始测试项目详情功能...\n');
  
  try {
    // 测试API
    console.log('📡 测试项目详情API...');
    const apiResult = await testProjectDetailAPI();
    console.log(`API状态码: ${apiResult.status}`);
    if (apiResult.status === 200) {
      console.log('✅ API响应正常');
      console.log(`项目名称: ${apiResult.data.name}`);
      console.log(`项目键: ${apiResult.data.key}`);
    } else {
      console.log('❌ API响应异常');
    }
    console.log('');
    
    // 测试页面渲染
    console.log('🌐 测试页面渲染...');
    const pageResult = await testPageRendering();
    console.log(`页面状态码: ${pageResult.status}`);
    console.log(`包含骨架屏: ${pageResult.hasSkeleton}`);
    console.log(`包含项目名称: ${pageResult.hasProjectName}`);
    console.log(`包含错误信息: ${pageResult.hasError}`);
    
    if (pageResult.hasSkeleton && !pageResult.hasProjectName) {
      console.log('\n⚠️  诊断结果: 页面卡在加载状态');
      console.log('可能的原因:');
      console.log('1. 前端JavaScript代码有问题');
      console.log('2. 数据获取逻辑错误');
      console.log('3. 组件渲染错误');
    } else if (pageResult.hasProjectName) {
      console.log('\n✅ 诊断结果: 页面正常工作');
    } else {
      console.log('\n❌ 诊断结果: 页面存在异常');
    }
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  }
}

runTests();